//
//  Login_Vm.swift
//  MikerShop
//
//  Created by eme on 2016/11/9.
//  Copyright © 2016年 eme. All rights reserved.
//

import RxSwift
import Result
import SwiftyJSON
import NetWorkCore
import ModelProtocol
import SwiftyUserDefaults
import BrandonCore
import UtilCore
/*
 owner:cy
 update:2016年11月09日15:15:21
 info: 登陆viewmodel
 */
class Login_Vm {
    
    let validatedUsername: Observable<ValidationResult>
    let validatedPassword: Observable<ValidationResult>
    // 表示btn 是否可以点击状态
    let signupEnabled: Observable<Bool>
    let signedIn: Observable<Result<UserModel,MikerError>>
    // Is signing process in progress
    let signingIn: Observable<Bool>
    private let disposeBag = DisposeBag()
    
    init(input: (
        username: Observable<String>,
        password: Observable<String>,
        loginTaps: Observable<Void>
        ),
         validationService: LoginValidationProtocol
        ) {
        validatedUsername = input.username.map{ username in
            return validationService.validateUsername(username)
        }.shareReplay(1)
        validatedPassword = input.password.map{ password in
            return validationService.validatePassword(password)
            }.shareReplay(1)
        let usernameAndPassword = Observable.combineLatest(input.username, input.password) { ($0, $1) }
        let signingIn = ActivityIndicator()
        self.signingIn = signingIn.asObservable()

        self.signedIn =  input.loginTaps.withLatestFrom(usernameAndPassword)
            .map{ username , password ->  UserApi in
                /// 只要登陆就需要重新生成devid
                let devid = NSUUID().uuidString
                Defaults[.uuid] = devid
                UtilCore.sharedInstance.devid = devid
                NetWorkAPI.sharedInstance.headers["devid"] = devid
                return UserApi.login(username: username, password: password)
        }
            .emeRequestApiForObj(UserModel.self, activityIndicator: signingIn)
            .shareReplay(1)
        self.signupEnabled = Observable.combineLatest(
            validatedUsername,
            validatedPassword,
            signingIn.asObservable()
        ){ username, password ,signingIn in
            username.isValid && password.isValid && !signingIn
            }
            .distinctUntilChanged()
            .shareReplay(1)
        
      
    }
    
}
